var accounts = require('./config').accounts
var loggerconfig = require('./config').logger
var task = require('./controller/task')
// var autoBuy = require('./controller/autoBuy')
// var app1 = require('child_process').fork('controller/autoBuy1.js')
var logger = require('./controller/log4js').getLogger()
var debuglogger = require('./controller/log4js').getLogger('debug')
const cluster = require('cluster')
const cpuNums = require('os').cpus().length

/*process.env.NODE_DEBUG='net';*/
if (cluster.isMaster) {
  var mount = 0
  // if (cpuNums < accounts.length) mount = cpuNums
  // else
  cluster.setupMaster({ exec: 'controller/autoBuy1.js' })

  mount = accounts.length
  for (let i = 0; i < mount; i++) {
    cluster.fork()
  }
  cluster.on('exit', worker => {
    debuglogger.debug(`worker${worker.id} exit.`)
  })
  cluster.on('fork', worker => {
    debuglogger.debug(`worker：worker${worker.id} created`)
  })

  cluster.on('disconnect', worker => {
    debuglogger.debug(`worker${worker.id} is disconnected.`)
  })
  cluster.on('listening', (worker, addr) => {
    debuglogger.debug(
      `worker${worker.id} listening on ${addr.address}:${addr.port}`
    )
  })
  cluster.on('online', worker => {
    debuglogger.debug(`worker${worker.id} is online now`)
  })

  cluster.on('message', (worker, msg) => {
    if (typeof msg === 'string')
      debuglogger.debug(`got the worker${worker.id}'s msg：${msg}`)
  })

  Object.keys(cluster.workers).forEach(id => {
    cluster.workers[id].send(`hello worker${id}`)
  })
}

logger.info('======', '自动抢购服务运行中..', '======')
